<template>
  <div class="add-news-container">
    <el-card class="box-card AddNewsContainer">
      <template #header>
        <div class="card-header">
          <span>{{ route.query.hid ? '修改新闻' : '发布新闻' }}</span>
        </div>
      </template>
      <el-form :rules="newsRules" :model="formData" ref="formRef" size="default" label-width="100px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入标题" size="large" clearable />
        </el-form-item>
        <el-form-item style="margin: 30px 0;" label="文章内容" prop="article">
          <el-input v-model="formData.article" type="textarea" :rows="8" placeholder="请输入文章内容" resize="none" />
        </el-form-item>
        <el-form-item label="文章类别" prop="type">
          <el-select v-model="formData.type" placeholder="请选择文章类别" style="width: 100%;">
            <el-option v-for="item in article" :label="item.name" :value="item.type" :key="item.type">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="button-group">
          <el-button @click="handlerCancel">取消</el-button>
          <el-button type="primary" @click="handlerSave">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
/**
 * 新闻发布/编辑页面组件
 * 用于发布新新闻或编辑已有新闻
 */
import { isUserOverdue } from '../../api/index'
import { getFindHeadlineByHid, saveOrAddNews, issueNews } from "../../api/index"
import { ref, onMounted } from "vue"
import { useRoute } from 'vue-router'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
const router = useRouter()
const route = useRoute()


const formRef = ref()
/**
 * 验证文章类别是否选择
 * @param {Object} rule - 验证规则
 * @param {*} value - 表单字段值
 * @param {Function} callback - 验证回调函数
 */
const validateType = (rule, value, callback) => {
  if (value) {
    callback()
  } else {
    callback(new Error('文章类别是必须的'))
  }
}
/**
 * 验证文章内容是否填写
 * @param {Object} rule - 验证规则
 * @param {*} value - 表单字段值
 * @param {Function} callback - 验证回调函数
 */
const validateArticle = (rule, value, callback) => {
  if (value && value.length > 0) {
    callback()
  } else {
    callback(new Error('文章内容是必须的'))
  }
}
/**
 * 验证文章标题是否填写
 * @param {Object} rule - 验证规则
 * @param {*} value - 表单字段值
 * @param {Function} callback - 验证回调函数
 */
const validateTitle = (rule, value, callback) => {
  if (value && value.length > 0) {
    callback()
  } else {
    callback(new Error('文章标题是必须的'))
  }
}
/**
 * 表单验证规则集合
 */
const newsRules = {
  title: [{ required: true, trigger: 'blur', validator: validateTitle }],
  article: [{ required: true, trigger: 'blur', validator: validateArticle }],
  type: [{ required: true, validator: validateType }],
}


/**
 * 表单数据模型
 */
const formData = ref({
  hid: null,
  title: "",   // 文章标题
  article: "", // 文章内容
  type: ""     // 文章类别
})
/**
 * 文章类别选项列表
 */
const article = [
  {
    type: "1",
    name: "新闻"
  },
  {
    type: "2",
    name: "体育"
  },
  {
    type: "3",
    name: "娱乐"
  },
  {
    type: "4",
    name: "科技"
  },
  {
    type: "5",
    name: "其他"
  }
]
/**
 * 修改新闻时的数据回显功能
 * 当路由包含hid参数时，获取对应新闻信息并填充到表单中
 */
const clickModifyEcho = async () => {
  if (!route.query.hid) return
  let result = await getFindHeadlineByHid(route.query.hid)
  formData.value.title = result.headline.title
  formData.value.article = result.headline.article

  formData.value.type = result.headline.type === 1 ? "1" :
    result.headline.type === 2 ? "2" :
      result.headline.type === 3 ? "3" :
        result.headline.type === 4 ? "4" : "5"
}
//页面挂载生命周期
onMounted(() => {
  clickModifyEcho()
})
/**
 * 取消按钮处理函数
 * 返回上一页
 */
const handlerCancel = () => {
  router.back()
}
/**
 * 保存按钮处理函数
 * 验证表单并提交数据到服务器
 */
const handlerSave = async () => {
  await formRef.value?.validate()
  //发送请求判断用户是否token过期
  await isUserOverdue()
  const Obj = { ...formData.value }

  //整理请求参数
  //  Obj.hid = userInfoStore.uid.toString()  //添加用户id 让后端知道谁添加的
  Obj.hid = route.query.hid  //添加用户id 让后端知道谁添加的
  // 判断type类型
  if (Obj.type == "新闻") Obj.type = "1"
  if (Obj.type == "体育") Obj.type = "2"
  if (Obj.type == "娱乐") Obj.type = "3"
  if (Obj.type == "科技") Obj.type = "4"
  if (Obj.type == "其他") Obj.type = "5"
  //发送请求
  if (route.query.hid) {
    await saveOrAddNews(Obj)
    ElMessage.success("修改成功")
  }
  else {
    await issueNews(formData.value)
    ElMessage.success("添加成功")
  }
  router.push({ name: "HeadlineNews" });
}


</script>

<style lang="less" scoped>
.add-news-container {
  padding: 20px 0;
}

.AddNewsContainer {
  width: 600px;
  margin: 0 auto;
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  :deep(.el-card__header) {
    background-color: #f5f7fa;
    border-bottom: 1px solid #ebeef5;
    padding: 15px 20px;
  }

  .card-header {
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }

  .button-group {
    display: flex;
    justify-content: flex-end;
    gap: 15px;
    margin-top: 40px;
  }
}
</style>